<template>
  <div
    ref="cardRef"
    class="draggable-card"
    :class="{ 'dragging': isDragging, 'selected': selected }"
    @mousedown="handleMouseDown"
    @click="handleClick"
  >
    <slot />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  index: {
    type: Number,
    required: true
  },
  selected: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['drag-start', 'drag-move', 'drag-end', 'click'])

const cardRef = ref()
const isDragging = ref(false)
const startPos = ref({ x: 0, y: 0 })
const currentPos = ref({ x: 0, y: 0 })

const handleMouseDown = (e) => {
  if (props.disabled) return
  
  isDragging.value = true
  startPos.value = { x: e.clientX, y: e.clientY }
  currentPos.value = { x: e.clientX, y: e.clientY }
  
  emit('drag-start', {
    index: props.index,
    startPos: startPos.value
  })
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  
  e.preventDefault()
}

const handleMouseMove = (e) => {
  if (!isDragging.value) return
  
  currentPos.value = { x: e.clientX, y: e.clientY }
  
  emit('drag-move', {
    index: props.index,
    currentPos: currentPos.value,
    delta: {
      x: currentPos.value.x - startPos.value.x,
      y: currentPos.value.y - startPos.value.y
    }
  })
}

const handleMouseUp = () => {
  if (!isDragging.value) return
  
  isDragging.value = false
  
  emit('drag-end', {
    index: props.index,
    startPos: startPos.value,
    endPos: currentPos.value
  })
  
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}

const handleClick = (e) => {
  if (!isDragging.value) {
    emit('click', e)
  }
}

onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
})
</script>

<style scoped>
.draggable-card {
  transition: all 0.3s ease;
  cursor: grab;
  user-select: none;
}

.draggable-card:hover {
  transform: translateY(-2px);
}

.draggable-card.dragging {
  cursor: grabbing;
  z-index: 1000;
  transform: rotate(5deg) scale(1.05);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.draggable-card.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.draggable-card:active {
  cursor: grabbing;
}
</style>
